import { Injectable } from '@nestjs/common';
import { UserAdmin_Create_Dto, UserAdmin_Find_Dto, UserAdmin_Update_Dto } from './assets/userAdmin.dto';
import { UserAdmin } from './assets/userAdmin.entity';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { Role } from '../role/assets/role.entity';
import {
  util_Db_Add,
  util_Db_AddAnyWhere,
  util_Db_Delete,
  util_Db_PageList,
  util_Db_Update,
} from '@/common/util/db';
import * as argon2 from 'argon2';
import { Class_HttpException_Base } from '@/common/classes/httpException';

@Injectable()
export class UserAdmin_Service {
  constructor(
    @InjectRepository(UserAdmin)
    private userAdmin_Repository: Repository<UserAdmin>,
    @InjectRepository(Role)
    private role_Repository: Repository<Role>,
  ) {}

  async userAdmin_Create(body: UserAdmin_Create_Dto) {
    const usered = await this.userAdmin_FindOneByQuery({
      userName: body.userName,
    });
    if (usered) throw new Class_HttpException_Base('已有该用户');
    body.password = await argon2.hash(body.password);
    const role = this.role_Repository.create({ id: body.roleId });
    return await util_Db_Add({
      createDto: { ...body, role },
      repository: this.userAdmin_Repository,
    });
  }

  async userAdmin_FindByPage(query: UserAdmin_Find_Dto) {
    const { size, page, userName } = query;
    return await util_Db_PageList<UserAdmin>({
      queryBuilder: this.userAdmin_Repository
        .createQueryBuilder('userAdmin')
        .leftJoin('userAdmin.role', 'role')
        .select([
          'userAdmin.id AS id',
          'userAdmin.userName AS userName',
          'userAdmin.avatar AS avatar',
          'userAdmin.statusUser AS statusUser',
          'userAdmin.createTime AS createTime',
          'role.id AS roleId',
          'role.roleName AS roleName',
        ]),
      query: { 'userAdmin.userName': userName, page, size },
      isRaw: true,
    });
  }

  async userAdmin_Update(body: UserAdmin_Update_Dto) {
    if (!body.userName) throw new Class_HttpException_Base('缺少更新的记录主键');
    const usered = await this.userAdmin_FindOneByQuery({
      userName: body.userName,
    });
    if (usered && usered.id !== body.id) throw new Class_HttpException_Base('该用户名已被占用');
    const role: Role = this.role_Repository.create({ id: body.roleId });
    return await util_Db_Update({
      findOne: () => this.userAdmin_FindOneByQuery({ id: body.id }),
      updateDto: { ...body, role },
      repository: this.userAdmin_Repository,
    });
  }

  async userAdmin_Remove(id: number) {
    return await util_Db_Delete({
      findOne: () => this.userAdmin_FindOneByQuery({ id }),
      id,
      repository: this.userAdmin_Repository,
    });
  }

  async userAdmin_FindOneByQuery(obj: UserAdmin_Find_Dto) {
    const queryBuilder = this.userAdmin_Repository
      .createQueryBuilder('userAdmin')
      .leftJoinAndSelect('userAdmin.role', 'role');
    const data = {
      'userAdmin.id': obj.id,
      'userAdmin.userName': obj.userName,
      'role.roleId': obj.roleId,
    };
    return await util_Db_AddAnyWhere<UserAdmin>({ queryBuilder, obj: data }).getOne();
  }
}
